#!/usr/bin/python -O

# $Id: tpa.py 232 2013-06-04 04:44:41Z chengxin.cai $

""" Python version of Text Protocol Adapter, 
    it uses XML-RPC to receive message
"""

from SimpleXMLRPCServer import SimpleXMLRPCServer as BaseServer

from amqp import RoutingKey, Sender
from protomsg import ProtoMsg 

class Server(BaseServer):
    def __init__(self, host, port):
        BaseServer.__init__(self, (host, port))

class Tpa(object):
    def __init__(self, host, port, protosrc):
        self.__sender = Sender(host, port, timeout=1)
        ProtoMsg.set_proto_path(opts.protoSrc)

    def accept(self, client, routing_key, msgstr):
        rKey = RoutingKey(routing_key)
        pMsg = ProtoMsg(rKey.package, rKey.publication)
        pMsg.fill_from_string(msgstr)

        self.__sender.send(rKey, pMsg.serialize_to_string())
        return 'OK'

    def echo(self, val):
        return val

# --main--
if __name__ == '__main__':
    import sys, os
    import socket
    from optparse import OptionParser

    parser = OptionParser()

    parser.add_option('--publish-ip',  dest = 'publish_ip', 
           action = 'store',  default = '127.0.0.1',
           help='ip address of the qpid server, [default: %default]')

    parser.add_option('--publish-port',  dest = 'publish_port', 
           action = 'store', type = int, default = 5672,
           help='port of the qpid server, [default: %default]')

    parser.add_option('--listen-ip',  dest = 'listen_ip', 
           action = 'store', default = '127.0.0.1',
           help='ip address used by the tpa server, [default: %default]')

    parser.add_option('--listen-port',  dest = 'listen_port', 
           action = 'store', type = int, default = 8000,
           help='port used by the tpa server, [default: %default]')

    parser.add_option('--proto-src',  dest ='protoSrc', 
          action='store', default = os.path.join(os.environ['HOME'], 'protos'),
          help='directory to store subscribe, default [%default]')

    (opts, args) = parser.parse_args()
 
    try:
        server = Server(opts.listen_ip, opts.listen_port)    

        server.register_introspection_functions()
        server.register_instance(Tpa(opts.publish_ip, 
                                 opts.publish_port, opts.protoSrc))

        if __debug__:
            print 'Start listening'

        server.serve_forever()

    except socket.error, e:
        print e
        sys.exit(1)

